package lambda;

/**
 * Create with IDEA
 * author:yangyangkun
 * Date:2019/4/9
 * Time:20:15
 */

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/***
 * java常用的四大内置函数式接口
 */

public class 四大函数式接口 {
    //Consumer<T> 消费型接口   有一个参数无返回值
    @Test
    public void test1(){
        happy(5000.0,(x) -> System.out.println("消费了"+ x +"元"));
    }
    public void happy(double money, Consumer<Double> con){
        con.accept(money);
    }
    //Supplier<T> 供给型函数接口   无参数，有一个返回值
    //需求：产生指定个数的整数，并放入集合中
    @Test
    public void test2(){
        List<Integer> list = getNumList(10,() -> (int)(Math.random() * 100));
        for (Integer li: list
        ) {
            System.out.println(li);
        }
    }
    public List<Integer> getNumList(int num,Supplier<Integer> sup){
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < num; i++){
            int n  =  sup.get();
            list.add(n);
        }
        return list;
    }
    //Function<T , R>:函数型接口  有参数有返回值
    //需求:去除字符串空格
    @Test
    public void test3(){
        String s = strHandler("\t\t\t\t\t你好你好你好     ",(str) -> str.trim() );
        System.out.println(s);
    }
    public String strHandler(String str, Function<String,String> fun){
        return fun.apply(str);
    }
    //Predicate<T> : 断言型接口
    //需求:将满足条件的字符串添加到集合中
    @Test
    public void test4(){
        List<String> list = Arrays.asList("Hello","Nihao","sa","adsa","wrs");
        List<String> list1 = filterStr(list,(y) -> y.length() > 3); //打印长度大于三的字符串
        for (String li: list1
             ) {
            System.out.println(li);
        }
    }
    public List<String> filterStr(List<String> list, Predicate<String> pre){
       List<String> stringList = new ArrayList<>();
        for (String string: list
             ) {
        if(pre.test(string)){
            stringList.add(string);
        }
        }
        return stringList;
    }
}
